package users

import (
	exc "hsy/app/exceptions"
	"hsy/app/models"
	request "hsy/app/requests"

	"github.com/gin-gonic/gin"
)

// Login 登录
func Login(c *gin.Context) {
	var r request.LoginRequest
	if err := c.Bind(&r); err != nil {
		exc.SendResponse(c, exc.ErrBind, nil)
		return
	}

	// Validte
	if msg, err := r.ValidateLogin(); err != nil {
		exc.SendValidResponse(c, msg)
		return
	}

	u := models.UserModel{
		Username: r.Username,
		Password: r.Password,
	}

	token, ok := u.Login(r.Username, r.Password)
	if ok {
		if err := u.UpdateToken(r.Username, token); err != nil {
			exc.SendResponse(c, exc.ErrDatabase, nil)
		} else {
			exc.SendResponse(c, exc.OK, models.LoginResponse{Token: token})
		}
		return
	}
	exc.SendResponse(c, exc.ErrPassword, nil)
}
